#!/bin/bash

# 容器环境下建议并发数：3-4（根据CPU核心数调整）
CONCURRENT=3
# 线程启动间隔（秒）：错开启动时间，避免同时冲击文件系统
START_DELAY=0.5
# 每个包处理后的缓冲时间（秒）
POST_DELAY=0.3
# 重试阈值
MAX_RETRY_THRESHOLD=10

# 包列表（保持不变）
PACKAGES=(
    "planning-base"
    "planning-interface-base"
    "planning-open-space"
    "planning-planner-public-road"
    "planning-lane-follow-map"
    "planning"
    "planning-task-piecewise-jerk-speed"
    "planning-task-rule-based-stop-decider"
    "planning-task-open-space-trajectory-partition"
    "planning-task-piecewise-jerk-speed-nonlinear"
    "planning-task-path-reference-decider"
    "planning-task-lane-borrow-path"
    "planning-task-path-decider"
    "planning-task-speed-bounds-decider"
    "planning-task-path-time-heuristic"
    "planning-task-open-space-fallback-decider"
    "planning-task-st-bounds-decider"
    "planning-task-pull-over-path"
    "planning-task-reuse-path"
    "planning-task-open-space-pre-stop-decider"
    "planning-task-open-space-trajectory-provider"
    "planning-task-fallback-path"
    "planning-task-lane-change-path"
    "planning-task-lane-follow-path"
    "planning-task-speed-decider"
    "planning-task-open-space-roi-decider"
    "planning-task-rss-decider"
    "planning-task-fast-stop-trajectory-fallback"
    "planning-traffic-rules-yield-sign"
    "planning-traffic-rules-keepclear"
    "planning-traffic-rules-rerouting"
    "planning-traffic-rules-backside-vehicle"
    "planning-traffic-rules-traffic-light"
    "planning-traffic-rules-reference-line-end"
    "planning-traffic-rules-crosswalk"
    "planning-traffic-rules-stop-sign"
    "planning-traffic-rules-destination"
    "planning-scenario-yield-sign"
    "planning-scenario-valet-parking"
    "planning-scenario-park-and-go"
    "planning-scenario-traffic-light-protected"
    "planning-scenario-emergency-pull-over"
    "planning-scenario-lane-follow"
    "planning-scenario-traffic-light-unprotected-left-turn"
    "planning-scenario-pull-over"
    "planning-scenario-bare-intersection-unprotected"
    "planning-scenario-emergency-stop"
    "planning-scenario-traffic-light-unprotected-right-turn"
    "planning-scenario-stop-sign-unprotected"
)

# 日志目录
LOG_DIR="./reinstall_logs"
mkdir -p "$LOG_DIR"
rm -f "$LOG_DIR"/*.log

FAILED_PACKAGES=()
FINAL_FAILED=()

echo "带延迟控制的多线程安装：并发数=$CONCURRENT，启动间隔=$START_DELAY秒"
echo "日志目录：$LOG_DIR"
echo "----------------------------------------"

# 处理单个包（带后置延迟）
process_package() {
    local package=$1
    local log_file="$LOG_DIR/${package}.log"
    
    echo "开始处理：$package（日志：$log_file）"
    buildtool reinstall "$package" > "$log_file" 2>&1
    
    if [ $? -eq 0 ]; then
        echo "✅ 成功：$package"
    else
        echo "❌ 失败：$package"
        FAILED_PACKAGES+=("$package")
    fi
    
    # 包处理完成后添加缓冲延迟
    sleep $POST_DELAY
}

# 多线程启动（带错开延迟）
index=0
total=${#PACKAGES[@]}

while [ $index -lt $total ]; do
    # 本轮启动的包数量（不超过剩余包数和并发数）
    current_batch=$(( CONCURRENT < (total - index) ? CONCURRENT : (total - index) ))
    
    # 逐个启动线程，每个间隔START_DELAY秒
    for ((i=0; i<current_batch; i++)); do
        pkg="${PACKAGES[index + i]}"
        process_package "$pkg" &
        # 错开启动时间（最后一个线程不延迟，避免多余等待）
        if [ $i -lt $((current_batch - 1)) ]; then
            sleep $START_DELAY
        fi
    done
    
    # 等待本轮所有线程完成
    wait
    
    # 移动到下一批
    index=$((index + current_batch))
done

# 重试失败的包（单线程+延迟）
if [ ${#FAILED_PACKAGES[@]} -le $MAX_RETRY_THRESHOLD ] && [ ${#FAILED_PACKAGES[@]} -gt 0 ]; then
    echo "----------------------------------------"
    echo "开始重试失败的${#FAILED_PACKAGES[@]}个包（单线程+延迟）..."
    for package in "${FAILED_PACKAGES[@]}"; do
        log_file="$LOG_DIR/${package}_retry.log"
        echo "重试处理：$package（日志：$log_file）"
        buildtool reinstall "$package" > "$log_file" 2>&1
        if [ $? -ne 0 ]; then
            FINAL_FAILED+=("$package")
        fi
        sleep $((POST_DELAY + 0.2))  # 重试时延迟稍长
    done
else
    FINAL_FAILED=("${FAILED_PACKAGES[@]}")
fi

# 结果统计
echo "----------------------------------------"
echo "总进度：$total 个包，成功 $((total - ${#FINAL_FAILED[@]})) 个，失败 ${#FINAL_FAILED[@]} 个"
if [ ${#FINAL_FAILED[@]} -gt 0 ]; then
    echo "失败列表：${FINAL_FAILED[@]}"
    echo "日志位置：$LOG_DIR"
else
    echo "🎉 所有包安装成功！"
fi
